package com.one.controller;

import com.one.dto.AdminLoginDTO;
import com.one.entity.Admin;
import com.one.properties.JwtProperties;
import com.one.result.Result;
import com.one.service.AdminService;
import com.one.utils.JwtUtil;
import com.one.vo.AdminLoginVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@Api(tags = "管理员相关接口")
@RestController
@RequestMapping("/admins")
public class AdminController {
    @Autowired
    private AdminService adminService;

    @Autowired
    private JwtProperties jwtProperties;

    @ApiOperation( "管理员登录接口")
    @PostMapping("/getAdminsByCodeByPass")
    public AdminLoginVO login(@RequestBody AdminLoginDTO adminLoginDTO) {
        log.info("管理员登录请求：{}", adminLoginDTO);
        Admin admin = adminService.login(adminLoginDTO);
        if(admin==null) return null;
        // 登录成功后，生成jwt令牌
        Map<String, Object> claims = new HashMap<>();
        claims.put("adminId", admin.getAdminId());
        claims.put("adminCode", admin.getAdminCode());
        String token = JwtUtil.createJWT(
                jwtProperties.getUserSecretKey(),
                jwtProperties.getUserTtl(),
                claims);
        AdminLoginVO adminLoginVO = AdminLoginVO.builder()
                .adminId(admin.getAdminId())
                .adminCode(admin.getAdminCode())
                .token(token)
                .build();
        return adminLoginVO;
    }

}
